//
//  HMSQLiteManager.swift
//  iOSWeibo12
//
//  Created by Admin on 16/9/27.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import FMDB

class HMSQLiteManager: NSObject {
    static let shared = HMSQLiteManager()
    
    var dbQueue: FMDatabaseQueue
    
    override init() {
        let dbPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).last!.appending("/status.db")
        
        print("dbPath: \(dbPath)")
        
        dbQueue = FMDatabaseQueue(path: dbPath)
        
        super.init()
        // 创建数据表
        createTable()
    }
    
    private func createTable() {
        // 之前的sql语句都是在代码里面在写的,通过文件来加载sql语句,在文件中可以编写多条sql语句
        
        // 获取table.sql文件的路径
        let bundlePath = Bundle.main.path(forResource: "tables", ofType: "sql")!
        
        // 加载table.sql文件里的内容
        let sql = try! String(contentsOfFile: bundlePath)
        print("加载文件sql: \(sql)")
        
        dbQueue.inDatabase { (db) -> Void in
            if let db = db, db.executeStatements(sql) {
                print("创建表成功")
            }
        }
    }
}
